#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Data  :     2020/4/28 下午2:15
--------------------------------------
"""
import smtplib
import time
from email.header import Header
from email.mime.text import MIMEText
import requests
from bs4 import BeautifulSoup
from dominate.tags import *
from dominate.util import raw

# 自动发送邮件
class SendEmail():
    def send_email(self):

        # 读取html文件内容
        with open(r'result.html','rb') as f:
            mail_body = f.read()

        # 发件人地址
        send_addr = 'jichaosong2020@foxmail.com'
        # 收件人地址
        reciver_addr = ['841734750@qq.com',"349770991","songjichao@ececloud.cn"]
        # reciver_addr = '349770991@qq.com'
        # 发送邮箱的服务器地址 qq邮箱是'smtp.qq.com', 136邮箱是'smtp.136.com'
        mail_server = 'smtp.qq.com'
        # now = time.strftime("%Y-%m-%d %H:%M:%S")
        now = time.strftime("%Y-%m-%d")
        # 邮件标题
        subject = '九价疫苗相关信息' + now
        # 发件人的邮箱及邮箱授权码
        username = '306333246@qq.com'
        password = 'ycxwrecxjjhgcafa'  # 注意这里是邮箱的授权码而不是邮箱密码
        # 邮箱的内容和标题
        message = MIMEText(mail_body, 'html', 'utf8')
        message['Subject'] = Header(subject, charset='utf8')
        message['TO'] = Header(",".join(reciver_addr))

        # 发送邮件，使用的使smtp协议
        smtp = smtplib.SMTP()
        smtp.connect(mail_server)
        smtp.login(username, password)
        smtp.sendmail(send_addr, reciver_addr, message.as_string())
        smtp.quit()


def getinfo():

    url = "http://hz.bendibao.com/live/yiliaojiankang/"

    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, "
                      "like Gecko) Chrome/73.0.3683.86 Safari/537.36"
    }

    res = requests.get(url, headers=headers)

    # print(res.text)

    res.encoding = res.apparent_encoding

    soup = BeautifulSoup(res.text, "lxml")
    n = 1
    title = soup.find_all("div", class_= "info")
    info = []
    for i in title:
        share = {}
        share['id'] = n
        share['url'] = i.a['href']
        share['title'] = i.a.string
        share['time'] = i.find("p", class_="from").text
        info.append(share)
        n += 1
    return info

def senddata():
    listdata = []
    for i in getinfo():
        if "九价" in i['title'] and "预约" in i['title']:
            listdata.append(i)

    return listdata


def sendemail():
    senddata()
    h = html()
    with h.add(body()):
        h2("九价疫苗相关信息")
        style(type='text/css')
        meta(http_equiv = "Content-Type", content="text/html; charset=utf-8")
        uls = ul()
        for item in range(len(senddata())):
            with uls:
                # li("序号:", item+1, style = "list-style: none")
                li(senddata()[item]['title'],style = "list-style: none")
                li(a(senddata()[item]['url'], herf = senddata()[item]['url'], target="_blank"),style = "list-style: none")
                li("发布时间:", senddata()[item]['time'], style = "list-style: none")
                hr()
    with open('./result.html','w') as f:
        f.write(h.render())


def sendfile():
    import paramiko

    hostname = '192.168.7.129'            #此处是linux的ip

    port = 22

    username = 'root'

    password = '123'

    t = paramiko.Transport((hostname, port))    #实现ftp功能，声明ftp实例

    t.connect(username=username, password=password)

    sftp = paramiko.SFTPClient.from_transport(t)

    sftp.put(r'D:\python\定时\Desktop\1.py', '/root/1.py')  #上传和下载只需要更改前后顺序

    sftp.close()

if __name__ == '__main__':
    print("==================程序正在运行==================")
    while True:
        now = time.strftime("%H")
        if (now == "09" or now == "13" or now == "16") and time.strftime("%M:%S") == "00:00":
            sendemail()
            SendEmail().send_email()
            print("发送成功  %s" %time.strftime("%Y-%m-%d %H:%M:%S"))